/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-11-25 13:02:04
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.bean.*;
import com.joysuch.wwyt.bp.bean.BpDepartBean.SearchDepartBean;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.service.BpDepartService;
import com.joysuch.wwyt.core.bean.SimpleInfoBean;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.repeatsubmit.NoRepeatSubmit;
import com.joysuch.wwyt.risk.entity.vo.DepartBatchDeleteCheckResult;
import com.joysuch.wwyt.risk.entity.vo.DepartDeleteCheckVO;
import com.joysuch.wwyt.risk.entity.vo.RiskPointDeleteCheckVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.omg.CORBA.portable.ValueOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/bp/depart")
@Api(tags = "部门管理")
public class BpDepartController {

    private static final Logger logger = LoggerFactory.getLogger(BpDepartController.class);

    @Autowired
    private BpDepartService bpDepartService;

    @PostMapping("add")
    @NoRepeatSubmit(paramNames = "parentId,name")
    public Object add(@RequestBody @Valid BpDepart entity) {
        bpDepartService.add(entity);
        return ResultBean.success("");
    }

    @PostMapping("update")
    public Object update(@RequestBody @Valid BpDepart entity) {

        if (entity.getId() == null) {
            return ResultBean.fail(102, "未指定主键");
        }
        bpDepartService.update(entity);
        return ResultBean.success("");

    }

    @GetMapping("page")
    public ResultBean page(Pageable page) {
        BpDepartBean data = bpDepartService.findByPage(page);
        return ResultBean.wrapSuccessfulResult(data);
    }

    @GetMapping("get")
    public ResultBean get(Long id, Pageable page) {
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<BpDepartListBean> bpDeparts = bpDepartService.get(id, page);
        return ResultBean.pageData(bpDeparts.getContent(), bpDeparts.getTotalElements());
    }


    @GetMapping("getDepartList")
    @ApiOperation(value = "获取部门树形结构")
    public ResultBean getDepartList() {
        List<BpDepartTreeBean> list = bpDepartService.getDepartList();
        return ResultBean.success(list);
    }


    @GetMapping("getListByParentId")
    @ApiOperation(value = "获取父部门下所属部门")
    public ResultBean getListByParentId(Pageable page, BpDepartSearchBean bean) {
        Page<BpDepartListBean> p = bpDepartService.getListByParentId(page, bean);
        return ResultBean.pageData(p.getContent(), p.getTotalElements());
    }


    @GetMapping("simple-list")
    public Object simpleList() {
        try {
            // 分页查询
            List<SimpleSelectListBean> data = bpDepartService.getList();
            return ResultBean.pageData(data, data.size());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @GetMapping("permission-simple-page")
    public Object permissionSimpleList(Pageable page, SearchDepartBean condition) {
        try {
            // 分页查询
            Page<SimpleInfoBean> data = bpDepartService.getDeptPmsList(page, condition);
            return ResultBean.pageData(data);
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @GetMapping("permission-list")
    public Object permissionList() {
        try {
            // 分页查询
            List<SimpleSelectListBean> data = bpDepartService.getDeptPmsList();
            return ResultBean.pageData(data, data.size());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @RequestMapping("simple-page")
    public Object simplePage(Pageable page, SearchDepartBean condition) {
        try {
            // 分页查询
            Page<SimpleInfoBean> data = bpDepartService.findByPageSimple(page, condition);
            return ResultBean.pageData(data);
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @PostMapping("delete")
    public Object delete(Long id) {
        try {
            bpDepartService.delete(id);
        } catch (ApiBusinessException e) {
            if (e.getCode() == Status.DELETE_CHECK_FAILED.getCode() && StringUtils.isNotEmpty(e.getMessage())) {
                List<DepartDeleteCheckVO> list = Lists.newArrayList();
                DepartDeleteCheckVO vo = JSONObject.parseObject(e.getMessage(), DepartDeleteCheckVO.class);
                list.add(vo);
                return ResultBean.fail(e.getCode(), "", list);
            } else {
                return ResultBean.fail(e.getCode(), e.getMessage());
            }
        }
        return ResultBean.success("");
    }

    @PostMapping("deleteByIds")
    @RequiresPermissions("bp:enterprise:depart:batch-delete")
    public ResultBean deleteByIds(@RequestBody List<Long> ids) {
        List<String> message = null;
        try {
            message = bpDepartService.deleteByIds(ids);
        } catch (ApiBusinessException e) {
            if (e.getCode() == Status.DELETE_CHECK_FAILED.getCode() && StringUtils.isNotEmpty(e.getMessage())) {
                DepartBatchDeleteCheckResult result = new DepartBatchDeleteCheckResult();
                List<DepartDeleteCheckVO> vos = JSONObject.parseArray(e.getMessage(), DepartDeleteCheckVO.class);
                result.setVos(vos);
                result.setSuccessNum(Math.max(ids.size() - vos.size(), 0));
                return ResultBean.fail(e.getCode(), "", result);
            } else {
                return ResultBean.fail(e.getCode(), e.getMessage());
            }
        }
        return ResultBean.success(message);
    }

    @GetMapping("getUser")
    public ResultBean getUser() {
        DpDepartUserBean user = bpDepartService.getUser();
        return ResultBean.wrapSuccessfulResult(user);
    }

    @GetMapping("getDepartDutyUser")
    public ResultBean getDepartDutyUser(Long departId) {
        return bpDepartService.getDepartDutyUser(departId);
    }

    @GetMapping("getDepartByUserId")
    @ApiOperation(value = "根据用户Id获取部门", response = BpDepart.class)
    public ResultBean getDepartByUserId(Long userId) {
        return bpDepartService.getDepartByUserId(userId);
    }

    @GetMapping("getNDepartDutyUser")
    @ApiOperation("获取当前部门/人员的上几级部门的负责人")
    public ResultBean getNDepartDutyUser(DepartDutyUserBean bean) {
        return bpDepartService.getNDepartDutyUser(bean);
    }


}
